package com.easyadmin.common.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;


public class SendMsg {

    public static void SendDingDing(String string) throws Exception {

        Long timestamp = System.currentTimeMillis();
        // 这个就是上面加签的密钥
        String secret = "SEC6bec587772a1ef4e6264c9a7029c5c286cb9c2ae01893171eb309508596a0620";
        String stringToSign = timestamp + "\n" + secret;

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

        // 这里就是消息的类型。详见https://open.dingtalk.com/document/orgapp/robot-message-types-and-data-format
        JSONObject json = new JSONObject();
        json.put("msgtype", "text");
        json.put("text", new JSONObject() {{
            put("content", string);
        }});

        // 这个就是上面创建机器人webhook后面的token
        String accessToken = "838f8c0e74d69ac29acbf896b3eb68764a6b2edd00940c813684b2473b76c0e3";
        String url = "https://oapi.dingtalk.com/robot/send"
                + "?access_token=" + accessToken
                + "&timestamp=" + timestamp
                + "&sign=" + sign;
        String get = HttpUtil.createPost(url)
                .body(json.toString())
                .execute().body();
        System.out.println(get);
    }
}
